﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace BLL.CSocket
{
    public class DESCrypt
    {
        private static string _DESKey = "";

        public static string DESKey
        {
            get { return _DESKey; }
            set { _DESKey = value; }
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="toEncrypt"></param>
        /// <returns></returns>
        public static byte[] DESEncrypt(byte[] inputByte)
        { 
            //定义DES加密服务提供类
            DESCryptoServiceProvider descryp = new DESCryptoServiceProvider();
            descryp.Padding = PaddingMode.Zeros;
            //加密密匙转化为byte数组
            byte[] key = Encoding.ASCII.GetBytes(_DESKey); //DES密钥（必须8字节）
            ICryptoTransform icryp = descryp.CreateEncryptor(key, key);//创建加密对象
            //获取加密后的字节
            byte[] enb = null;
            try
            {
                enb = icryp.TransformFinalBlock(inputByte, 0, inputByte.Length);
            }
            catch
            {
                return null;
            }

            return enb;
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="deStr">进行解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public static byte[] DESDecrypt(byte[] deb)
        { 
           //实例化DES加密对象
            DESCryptoServiceProvider descrypt = new DESCryptoServiceProvider();
            descrypt.Padding = PaddingMode.Zeros;
            

            descrypt.Mode = CipherMode.CBC;            
            //加密密匙转化为byte数组
            byte[] key = Encoding.ASCII.GetBytes(_DESKey); //DES密钥（必须8字节）
            //创建加密对象
            ICryptoTransform icryp = descrypt.CreateDecryptor(key, key);

            //获取解密后的字节
            byte[] de = null;
            try
            {
                de = icryp.TransformFinalBlock(deb, 0, deb.Length);
            }
            catch
            {
                return null;
            }

            return de;
        }
    }
}
